package com.bolun998300.personal_blog_springboot.controller.background;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.bolun998300.personal_blog_springboot.Utils.IpUtil;
import com.bolun998300.personal_blog_springboot.Utils.Result;
import com.bolun998300.personal_blog_springboot.pojo.Bbs;
import com.bolun998300.personal_blog_springboot.pojo.Blog;
import com.bolun998300.personal_blog_springboot.pojo.Comment;
import com.bolun998300.personal_blog_springboot.service.BbsService;

@RestController
public class BbsController {
	
	@Autowired
	private BbsService bbsService;
	
	@GetMapping(value = "/bbses/listByPage/{operate}")
    public HashMap<String,Object> listByPage(int page , int limit, @PathVariable String operate){
        Page<Bbs> pageFromJpa = bbsService.listByPage(page,limit,operate);
        List<Bbs> list = pageFromJpa.getContent();
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageFromJpa.getTotalElements());
        map.put("data",pageFromJpa.getContent());
        map.put("pages",pageFromJpa.getTotalPages());
        return map;
    }
	
	@PutMapping(value = "/bbses/{operate}")
    public Object update(@PathVariable String operate, HttpServletRequest request){
        String[] ids = request.getParameterValues("ids");
        for(int i = 0;i < ids.length;i++){
            int id = Integer.parseInt(ids[i]);
            Bbs bbs = bbsService.get(id);
            if("bbsIsNotPass".equals(operate)){
                bbs.setBbsState(-1);
            }else {
            	bbs.setBbsState(1);
            }
            bbsService.update(bbs);
        }
        return Result.success();
    }

    @PostMapping("/bbses/addBbs")
	public Object add(@RequestBody Bbs bbs, HttpServletRequest request){
        String userIp=IpUtil.getIpAddr(request);
        bbs.setBbsUserIp(userIp);
        bbs.setBbsState(0);
        bbs.setBbsDate(new Date());
        bbsService.save(bbs);
        return Result.success();
    }
	
	
	
	
	
}
